#!/usr/bin/ruby
# Author: Jimmy Saw
# Last updated: 12-29-2010
# Usage: dissertation_KeggModule.rb <KEGG module name>
# Example: dissertation_KeggModule.rb M00001

require 'bio'
require 'soap/wsdlDriver'

wsdl = "http://soap.genome.jp/KEGG.wsdl"
serv = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
serv.generate_explicit_type = true

entry = ARGV[0]

#Get module entry from KEGG
et = serv.bget("md:#{entry}")

#Set up MODULE object
o = Bio::KEGG::MODULE.new(et)

#Read ORTHOLOGY info from MODULE entry
orthology = o.orthologs_as_array

#Print MODULE entry and name
print "Module info:\n"
print "MD:", "\t", o.entry_id, "\t", o.name, "\n"

print "\n"

#Set up ORTHOLOGs from MODULE as hash
orth = o.orthologs_as_hash
key = orth.keys
val = orth.values

#Print a list of KOs 
print "KO info:\n"
for i in 0..key.length
  if key[i] =~ /^K0/ 
    print "KO:", "\t", key[i], "\t", val[i], "\n"
  end
end

print "Total KOs found: #{key.length}\n"

print "\n"

#Print COGs found for each KO 
print "COG info:\n"

cogcount = 0

orthology.each do |oo|
  f = serv.bget("orthology:#{oo}")
  ot = Bio::KEGG::ORTHOLOGY.new(f)
  oid = ot.entry_id
  odf = ot.definition

  cs = ot.dblinks_as_strings
  for s in cs
    if s =~ /COG/
      cogcount += 1
      slice = s.split(" ")
      if slice.length == 2
        print "COG:", "\t", oid, "\t", slice[1], "\t", odf, "\n"
      else
        for j in 1..slice.length
          if slice[j] != nil
            print "COG:", "\t", oid, "\t", slice[j], "\t", odf, "\n"
          end
        end
      end
    end
  end
end

print "Total COGs found: #{cogcount}\n"

